package kvoog.arkanoid.common;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.artemis.Component;

/**
 * This component provider always returns a new instance of a component. An instance
 * is created when requested and is of the type passed in to the constructor.
 * 
 * Ported from Ash entity component system framework for Action Script by Igor Knezevic. 
 * http://www.richardlord.net/blog/finite-state-machines-with-ash
 */
public class ComponentTypeProvider implements IComponentProvider {
	
	private Class<? extends Component> componentType;

	/**
	 * Constructor
	 *
	 * @param type The type of the instances to be created
	 */
	public ComponentTypeProvider(Class<? extends Component> type) {
		this.componentType = type;
	}

	/**
	 * Used to request a component from this provider
	 *
	 * @return A new instance of the type provided in the constructor
	 */
	@Override
	public Component getComponent() {
		Component instance = null;
		try {
			Constructor<? extends Component> ctor = componentType.getConstructor();
			instance = ctor.newInstance();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return instance;
	}

	/**
	 * Used to compare this provider with others. Any ComponentTypeProvider that returns
	 * the same type will be regarded as equivalent.
	 *
	 * @return The type of the instances created
	 */
	@Override
	public int getId() {
		// TODO Not yet implemented !
		return 0;
	}

}
